<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20231021
 * Time: 11:05 
 * 众筹管理
 */
namespace app\product\controller;

use  Mscore\Core\Controller;
use  app\product\model\Zerocontrol as ZerocontrolModel;
use  app\product\model\Common as CommonModel;
use  Mscore\Core\Lib\ArrayMethod;
use  app\admin\model\Login as LoginModel;
use  Mscore\Core\Lang;

class ZerocontrolController extends Controller{

	private $model;
    private $login;
    private $error;
    private $success;
    private $language;
    /**
     * 初始化自动连接方法
     * @param array $sysmod 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->login = (new LoginModel)->isAuth();
        if(isset($this->login['code'])&&$this->login['code']==401){
            echo json_encode($this->login);
            Header("Location:".config('server.login_url'));
            exit;
        }
        $this->model = new ZerocontrolModel;
        $this->language = isset($_COOKIE['language'])?$_COOKIE['language']:'default';
        Lang::init($this->language);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }   

    /**
     * 运营列表
     * @param array $list 
     * @param array $where 
     */ 
    public function list(){  
        //文章类
        $post = post();
        switch (true) {
            case $post:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' a.dels<1 ';
                if($this->login['info']['ranges']<1){
                    $where .= ' and a.aid = '.$this->login['info']['aid'];
                }
                if(post('title')){
                    $where .= ' and a.title like "%'.post('title').'%"';
                }
                if(post('procode')){
                    $where .= ' and a.procode like "%'.post('procode').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                $data = [
                    "code" => 200,
                    "data" => $datalist['datalist'],
                    "count"=> $datalist['total'],
                    "msg" => 'ok'
                ];
                $this->echojson($data);
                break;
            default:
                $this->display('list.html');
                break;
        }
    }

    /**
     * 添加
     * @param array $add 
     * @param array $where 
     */ 
    public function add(){
    	$params = post();
    	switch (true) {
    		case $params:
    			$data = $this->model->save($params);
                switch ($data) {
                    case true:
                        $this->echoJson($this->success);
                        break;
                    default:
                        $this->echoJson($this->error);
                        break;
                } 
    			break;
    		default:
    		    if(get('id')){
                    $datainfo =$this->model->info(get('id'));
                }
                $pro = (new CommonModel())->getZero('dels<1 and status<2','id,title,procode,beatpoint');
                if(!empty($pro)){
                    foreach ($pro as $key => $value) {
                        $value['beatpoint']=!empty($value['beatpoint'])?json_decode($value['beatpoint'],true):array();
                        $pro[$key]['beatpoint']=$value['beatpoint']['rands'].'-'.$value['beatpoint']['length'];
                    }
                }
                
                //定义变量datainfo输出
                $datainfo['id']=isset($datainfo['id'])?$datainfo['id']:'';
                $datainfo['title']=isset($datainfo['title'])?$datainfo['title']:'';
                if($this->login['info']['grade']!='superadmin'){
                   $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:$this->login['info']['aid'];
                   $datainfo['username']=isset($datainfo['username'])?$datainfo['username']:$this->login['info']['username'];
                }else{
                   $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:0;
                   $datainfo['username']=isset($datainfo['username'])?$datainfo['username']:'';
                }
                $datainfo['sell']=isset($datainfo['sell'])?$datainfo['sell']:array('min'=>0,'max'=>10,'trend'=>2,'unit'=>1,'length'=>2);
                $datainfo['ratio']=isset($datainfo['ratio'])?$datainfo['ratio']:array('min'=>10,'max'=>40);
                $datainfo['profitrate']=isset($datainfo['profitrate'])?$datainfo['profitrate']:array('min'=>10,'max'=>40,'symbol'=>1,'unit'=>1,'length'=>2);
                $datainfo['proid']=isset($datainfo['proid'])?$datainfo['proid']:0;
                $datainfo['procode']=isset($datainfo['procode'])?$datainfo['procode']:'';
                $datainfo['status']=isset($datainfo['status'])?$datainfo['status']:2;

                $this->assign('datainfo',$datainfo);
                $this->assign('grade',$this->login['info']['grade']);
                $this->assign('pro',$pro);
                $this->display('add.html');
    			break;
    	}
    }

    /**
     * 删除
     * @param array $del 
     * @param array $where 
     */
    public function del(){
        $data=$this->model->del(post('id',false));
        switch ($data) {
            case true:
                // $this->model->deldisk(' operate_id = '.post('id',false));
                $this->echoJson($this->success);
                break;
            default:
                $this->echoJson($this->error);
                break;
        } 
    }

    /**
     * 运营管控
     * @param array $controllist 
     * @param array $where 
     */ 
    public function controllist(){  
        //文章类
        $post = post();
        switch (true) {
            case $post:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' a.dels<1 and a.status = 1 ';
                if($this->login['info']['ranges']<1){
                    $where .= ' and a.aid = '.$this->login['info']['aid'];
                }
                if(post('title')){
                    $where .= ' and a.title like "%'.post('title').'%"';
                }
                if(post('username')){
                    $where .= ' and a.username like "%'.post('username').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                $data = [
                    "code" => 200,
                    "data" => $datalist['datalist'],
                    "count"=> $datalist['total'],
                    "msg" => 'ok'
                ];
                $this->echojson($data);
                break;
            default:
                $this->display('clist.html');
                break;
        }
    }

    /**
     * 运营管控
     * @param array $cshow 
     * @param array $where 
     */ 
    public function cshow(){  
        $params = post();
        switch (true) {
            case $params:
                if($params['sell']['min']>$params['sell']['max'] || $params['profitrate']['min']>$params['profitrate']['max'] || $params['ratio']['min']>$params['ratio']['max']){
                    $this->error['msg']='参数非法，有最小值参数大于最大值';
                    $this->echoJson($this->error);
                }
                $info = $this->model->savedisk($params);
                switch ($info) {
                    case true:
                        $this->echoJson($this->success);
                        break;
                    default:
                        $this->echoJson($this->error);
                        break;
                } 
                break;
            default:
                if(get('id')){
                    $datainfo =$this->model->info(get('id'));
                    $key = config('zerocontrol.key');
                    $info = $this->model->execRedis('hget',[$key,$datainfo['procode'].$datainfo['aid']]);
                }
                //定义变量datainfo输出
                $datainfo['id']=isset($datainfo['id'])?$datainfo['id']:'';
                $datainfo['title']=isset($datainfo['title'])?$datainfo['title']:'';
                $datainfo['aid']=isset($datainfo['aid'])?$datainfo['aid']:0;
                $datainfo['username']=isset($datainfo['username'])?$datainfo['username']:'';
                $datainfo['sell']=isset($datainfo['sell'])?$datainfo['sell']:array('min'=>0,'max'=>10,'trend'=>2,'unit'=>1,'length'=>2);
                $datainfo['ratio']=isset($datainfo['ratio'])?$datainfo['ratio']:array('min'=>10,'max'=>40);
                $datainfo['profitrate']=isset($datainfo['profitrate'])?$datainfo['profitrate']:array('min'=>10,'max'=>40,'symbol'=>1,'unit'=>1,'length'=>2);
                $datainfo['proid']=isset($datainfo['proid'])?$datainfo['proid']:0;
                $datainfo['procode']=isset($datainfo['procode'])?$datainfo['procode']:'';
                $datainfo['type']=isset($datainfo['type'])?$datainfo['type']:1;
                $datainfo['auto']=isset($datainfo['auto'])?$datainfo['auto']:1;
                $datainfo['timelong']=isset($datainfo['timelong'])?$datainfo['timelong']:60;
                $datainfo['starttime']=isset($datainfo['starttime'])?date('Y-m-d H:i:s',$datainfo['starttime']):date('Y-m-d H:i:s',time());
                $datainfo['status']=isset($datainfo['status'])?$datainfo['status']:2;
                $datainfo['run']=isset($info)&&!empty($info)?1:0;
                $datainfo['runtime']=0;
                $info=isset($info)&&!empty($info)?json_decode($info,true):[];
                $info['type']=isset($info['type'])?$info['type']:0;
                $info['starttime']=isset($info['starttime'])?$info['starttime']:0;
                $info['timelong']=isset($info['timelong'])?$info['timelong']:0;
                $this->assign('datainfo',$datainfo);
                $this->assign('info',$info);
                $this->display('cshow.html');
                break;
        }
    }

    /**
     * 更新运营
     * @param array $disk 
     * @param array $where 
     */ 
    public function diskinfo(){
        $operate=post();
        if (isset($operate['procode'])&&!empty($operate['procode'])) {
            $info = $this->model->execRedis('hget',[config('zerocontrol.runkey'),$operate['procode'].$operate['aid']]);
            $product = $this->model->execRedis('hget',[config('futures.zerotrade'),$operate['procode']]);
            $data=[];
            if(isset($info)&&!empty($info)&&isset($product)&&!empty($product)){
                $product=json_decode($product,true);
                $info=json_decode($info,true);
                switch ($info['type']) {
                    case 1:
                        $data['oldprice']=$product['price'];
                        $data['newprice']=$info['price'];
                        $data['rate']=($info['rate']*100).'%';
                        $data['info']=$info['info'];
                        break;
                    case 2:
                        $data['oldprice']=$product['price'];
                        $data['newprice']=round($product['price']+$info['difference'],$product['length']);
                        $data['rate']=$info['rate'].'%';
                        $data['info']=$info['info'];
                        break;
                    default:
                        $data['oldprice']=$product['price'];
                        $data['newprice']=$product['price'];
                        $data['rate']=0;
                        $data['info']='不控';
                        break;
                }
            }
            $this->success["data"]=$data;
            $this->echojson($this->success);
        }
        $this->echojson($this->error);
    }

    /**
     * 更新运营
     * @param array $disk 
     * @param array $where 
     */ 
    public function diskdel(){
        $operate=post();
        if (isset($operate['procode'])&&!empty($operate['procode'])) {
            $zero = config('zerocontrol');
            $this->model->execRedis('hdel',[$zero['key'],$operate['procode'].$operate['aid']]);
            $this->model->execRedis('hdel',[$zero['runkey'],$operate['procode'].$operate['aid']]);
            $this->echojson($this->success);
        }
        $this->echojson($this->error);
    }
    
    /**
     * 更新运营
     * @param array $disk 
     * @param array $where 
     */ 
    public function getconf(){
        $data=post();
        if (isset($data['id'])&&!empty($data['id'])) {
            $disk=$this->model->info($data['id'],'proid,sell,profitrate');
            $pro=(new CommonModel())->getZeroinfo('id='.$disk['proid'],'beatpoint');
            if(!empty($pro['beatpoint'])){
                $pro['beatpoint']=json_decode($pro['beatpoint'],true);
                $disk['sell']['unit']=$pro['beatpoint']['rands'];
                $disk['sell']['length']=$pro['beatpoint']['length'];
                $disk['profitrate']['unit']=$pro['beatpoint']['rands'];
                $disk['profitrate']['length']=$pro['beatpoint']['length'];
                $data=[
                    'id'=>$data['id'],
                    'sell'=>json_encode($disk['sell']),
                    'profitrate'=>json_encode($disk['profitrate'])
                ];
                $status=$this->model->updateconf($data);
                switch ($status) {
                    case true:
                        $this->echojson($this->success);
                        break;
                    default:
                        $this->echojson($this->error);
                        break;
                }     
            }else{
                $this->echojson($this->error);
            }
        }
        $this->echojson($this->error);
    }


}
